import React, {
  createContext,
  useState,
  useContext,
  ReactNode,
  FC,
} from 'react';

interface LoadingContextType {
  loading: boolean;
  showLoading: () => void;
  hideLoading: () => void;
  resetLoading: () => void;
}

const LoadingContext = createContext<LoadingContextType>({
  loading: false,
  showLoading: () => {},
  hideLoading: () => {},
  resetLoading: () => {},
});

interface LoadingProviderProps {
  children: ReactNode;
}

export const LoadingProvider: FC<LoadingProviderProps> = ({ children }) => {
  const [loadingCount, setLoadingCount] = useState(0);

  const showLoading = () => {
    setLoadingCount((prevCount) => prevCount + 1);
  };

  const hideLoading = () => {
    setLoadingCount((prevCount) => Math.max(0, prevCount - 1));
  };

  const resetLoading = () => {
    setLoadingCount(0);
  };

  const loading = loadingCount > 0;

  return (
    <LoadingContext.Provider
      value={{
        loading,
        showLoading,
        hideLoading,
        resetLoading,
      }}
    >
      {children}
      {loading && <div>loading...</div>}
    </LoadingContext.Provider>
  );
};

// 创建自定义Hook方便使用
export const useLoading = () => {
  const context = useContext(LoadingContext);
  if (!context) {
    throw new Error('useLoading must be used within a LoadingProvider');
  }
  return context;
};

// 保留原有的Loading组件作为展示组件
const Loading: FC = () => {
  const { loading } = useLoading();
  return loading ? <div>loading...</div> : null;
};

export default Loading;
